package com.demo.aidroid.activity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.drawable.AnimationDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.demo.aidroid.R;
import com.demo.aidroid.adapter.BookListAdapter;
import com.demo.aidroid.bean.Book;
import com.demo.aidroid.fragment.BookDetailFragment;
import com.demo.aidroid.services.IflyEngineService;
import com.demo.aidroid.util.Hanyu;
import com.demo.aidroid.util.ModelUtil;
import com.demo.aidroid.util.WebSocketTool;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

import static com.demo.aidroid.services.IflyEngineService.Begin_recognize;
import static com.demo.aidroid.services.IflyEngineService.Listen_recognize;
import static com.demo.aidroid.services.IflyEngineService.Listen_wake_up;
import static com.demo.aidroid.services.IflyEngineService.Speak_opening_remarks;
import static com.demo.aidroid.services.IflyEngineService.Speak_search_result;
import static com.demo.aidroid.services.IflyEngineService.VolumeChanged_recognize;

/**
 * Created by kevinLiao on 2017/7/19.
 */
public class MainActivity extends Activity implements Handler.Callback, BookListAdapter.OnItemClickListener {

    private final static int RETURN_TO_HOME_DELAY_SHORT = 5000;
    private final static int RETURN_TO_HOME_DELAY = 15000;
    private final static int START_LISTENER_TO_WAKE_UP = 0x900;
    private final static int RETURN_TO_HOME = 0x700;
    private final static int SHOW_RESULT = 0x701;

    @InjectView(R.id.ll_home)
    View llHome;
    @InjectView(R.id.ll_not_found_result)
    LinearLayout llNotFoundResult;
    @InjectView(R.id.rl_listen)
    RelativeLayout btnListen;
    @InjectView(R.id.img_gif)
    ImageView imgGif;

    @InjectView(R.id.ll_found_result)
    LinearLayout llFoundResult;
    @InjectView(R.id.list_book)
    RecyclerView listBook;

    private BookDetailFragment fragment;
    private BookListAdapter bookListAdapter;

    private Map<String, Book> bookResult = new LinkedHashMap<>();

    private Hanyu hanyu = new Hanyu();

    private Messenger mMessenger = null;
    private Messenger serverMessenger = null;

    private Handler mUiHandler;
    private Messenger webSocketMessenger;

    AnimationDrawable anim;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            String msgReceived = msg.getData().getString("resultString");
            switch (msg.what) {
                case Listen_wake_up:
                    String keyword = hanyu.getStringPinYin(msgReceived);
                    if (!TextUtils.isEmpty(msgReceived) && keyword.contains("duoduo")) {
                        sendOpeningRemarks();
                    } else {
                        mUiHandler.sendEmptyMessage(START_LISTENER_TO_WAKE_UP);
                    }
                    break;
                case Begin_recognize:
                    imgGif.setVisibility(View.VISIBLE);
                    llHome.setVisibility(View.INVISIBLE);
                    anim.start();
                    break;
                case VolumeChanged_recognize:
                    break;
                case Listen_recognize:
                    processData(msgReceived);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            serverMessenger = new Messenger(service);
            mMessenger = new Messenger(handler);
            mUiHandler.sendEmptyMessage(START_LISTENER_TO_WAKE_UP);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //  解除系统锁屏
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
                        WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        //  隐藏虚拟按键
        hideNavigation();
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);

        imgGif.setImageResource(R.drawable.animlist_gif);
        anim = (AnimationDrawable) imgGif.getDrawable();

        mUiHandler = new Handler(this);
        webSocketMessenger = new Messenger(mUiHandler);

        bookResult.putAll(ModelUtil.getBooks());
        bookListAdapter = new BookListAdapter(this);
        bookListAdapter.setOnItemClickListener(this);

        listBook.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        listBook.setAdapter(bookListAdapter);

        WebSocketTool.RegisterMessageCallback(webSocketMessenger);
        WebSocketTool.Connect();

        //  绑定讯飞语音服务
        bindService(new Intent(this, IflyEngineService.class), serviceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        WebSocketTool.Connect();
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case START_LISTENER_TO_WAKE_UP:
                sendWakeUpCommand();
                return true;
            case RETURN_TO_HOME:
                showHome();
                mUiHandler.sendEmptyMessage(START_LISTENER_TO_WAKE_UP);
                return true;
            case SHOW_RESULT:
                mUiHandler.removeMessages(RETURN_TO_HOME);
                mUiHandler.sendEmptyMessageDelayed(RETURN_TO_HOME, RETURN_TO_HOME_DELAY);
                return true;
            case WebSocketTool.TYPE_CONNECT:
                Log.d("Message Type", "TYPE_CONNECT");
                break;
            case WebSocketTool.TYPE_DISCONNECT:
                Log.d("Message Type", "TYPE_DISCONNECT");
                WebSocketTool.Connect();
                break;
            case WebSocketTool.TYPE_EXCEPTION:
                Log.e("Message Type", "TYPE_EXCEPTION");
                WebSocketTool.Connect();
                break;
        }
        return false;
    }

    @Override
    public void onItemClick(RecyclerView.ViewHolder holder, int position) {
        bookListAdapter.setItemSelectedEntity(position);
        Book book = bookListAdapter.getItem(position);
        fragment.setData(book);

        mUiHandler.sendEmptyMessage(SHOW_RESULT);
    }

    /**
     * 发送唤醒命令
     */
    private void sendWakeUpCommand(){
        Message message = Message.obtain();
        message.what = Listen_wake_up;
        message.replyTo = mMessenger;
        try {
            serverMessenger.send(message);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送欢迎语
     */
    private void sendOpeningRemarks() {
        Message message = Message.obtain();
        message.what = Speak_opening_remarks;
        message.replyTo = mMessenger;
        Bundle bundle = new Bundle();
        String[] stringArray = getResources().getStringArray(R.array.hello_words);
        bundle.putString("openingRemarks", stringArray[0]);
        message.setData(bundle);
        try {
            serverMessenger.send(message);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private void processData(String stringReceived) {

        WebSocketTool.Send(stringReceived);

        List<Book> bookFound = new ArrayList<>();
        for(String key : bookResult.keySet()) {
            if (stringReceived.contains(key)) {
                bookFound.add(bookResult.get(key));
            }
        }

        String searchResult = "";
        if (bookFound.size() > 0) {
            searchResult = getString(R.string.book_found);
            showBookResult(bookFound);
        } else {
            searchResult = getString(R.string.book_not_found);
            showNotFoundResult();
        }

        anim.stop();
        imgGif.setVisibility(View.INVISIBLE);

        sendSearchResultString(searchResult);
    }

    /**
     * 发送查询结果字符串
     */
    private void sendSearchResultString(String resultStr){

        Message message = Message.obtain();
        message.what = Speak_search_result;
        message.replyTo = mMessenger;
        Bundle bundle = new Bundle();
        bundle.putString("resultString", resultStr);
        message.setData(bundle);
        try {
            serverMessenger.send(message);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 点击唤醒
     */
    @OnClick(R.id.ll_home)
    void onListen() {
        sendOpeningRemarks();
    }

    /**
     * 显示主界面
     */
    private void showHome() {
        llHome.setVisibility(View.VISIBLE);
        imgGif.setVisibility(View.INVISIBLE);
        llNotFoundResult.setVisibility(View.GONE);
        llFoundResult.setVisibility(View.GONE);
    }

    /**
     * 显示已找到结果页
     */
    private void showBookResult(List<Book> books) {
        llHome.setVisibility(View.GONE);
        imgGif.setVisibility(View.INVISIBLE);
        llFoundResult.setVisibility(View.VISIBLE);
        llNotFoundResult.setVisibility(View.GONE);

        Book book = books.get(0);
        book.setSelected(true);

        bookListAdapter.setList(books);
        bookListAdapter.notifyDataSetChanged();

        fragment = new BookDetailFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("book", book);
        fragment.setArguments(bundle);
        getFragmentManager().beginTransaction().replace(R.id.fl_book_detail, fragment).commit();

        mUiHandler.sendEmptyMessage(SHOW_RESULT);
    }

    /**
     * 显示未找到
     */
    public void showNotFoundResult() {
        llHome.setVisibility(View.INVISIBLE);
        imgGif.setVisibility(View.INVISIBLE);
        llFoundResult.setVisibility(View.INVISIBLE);
        llNotFoundResult.setVisibility(View.VISIBLE);

        mUiHandler.sendEmptyMessageDelayed(RETURN_TO_HOME, RETURN_TO_HOME_DELAY_SHORT);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMessenger = null;
        serverMessenger = null;

        WebSocketTool.RemoveMessageCallback(webSocketMessenger);
        webSocketMessenger = null;
        unbindService(serviceConnection);
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    private void hideNavigation() {
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    long firstTime;
    /**
     * 打开设置
     */
    @OnClick(R.id.btn_setting)
    void onSetting() {
        if((System.currentTimeMillis()- firstTime) > 1000){
            firstTime = System.currentTimeMillis();
        } else {
            openSetting();
        }
    }

    /**
     * 屏蔽返回键
     * @param keyCode
     * @param event
     * @return
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //屏蔽menu
    @Override
    public void onWindowFocusChanged(boolean pHasWindowFocus) {
        super.onWindowFocusChanged(pHasWindowFocus);
        if (!pHasWindowFocus) {
            sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
        }
    }


    private void openSetting() {
        Intent intent = new Intent(Settings.ACTION_SETTINGS);
        startActivity(intent); // 打开系统设置界面
    }
}
